<?php
/**
 * URL重定向
 * @param string $url 重定向的URL地址
 * @param integer $time 重定向的等待时间（秒）
 * @param string $msg 重定向前的提示信息
 * @return void
 */
function redirect($url, $time=0, $msg='') {
	//多行URL地址支持
	$url = str_replace(array("\n", "\r"), '', $url);
	if (empty($msg))
	$msg = "The system will jump to {$url} after {$time} seconds!";
	if(!headers_sent()) {
		header( "HTTP/1.1 301 Moved Permanently" );
		header("Cache-Control: no-cache, must-revalidate");
		// redirect
		if (0 === $time) {
			header('Location: ' . $url);
		} else {
			header("refresh:{$time};url={$url}");
			echo($msg);
		}
		exit();
	}else{
		$str    = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
		if ($time != 0)
		$str .= $msg;
		exit($str);
	}
}


/**
 *连续创建目录
 *
 *@param string $dir 目录字符串
 *@param int $mode 权限数字
 *@return boolean
 */
function make_dir($dir){
	if(!$dir)
	return 0;
	$dir = str_replace("\\","/",$dir);
	$mdir = "";
	foreach(explode("/",$dir) as $val){
		$mdir .= $val."/";
		if($val==".."||$val=="."||trim($val)=="")
		continue;
		if(!file_exists($mdir)){
			if(!@mkdir($mdir)){
				return false;
			}else{
				@chmod($mdir,0777);
			}
		}
	}
	return true;
}


/**
 *递归获取目录下的文件地址
 */
function tree($directory){
	static $dir_arr;
	$mydir = dir($directory);
	while($file = $mydir->read()){
		if((is_dir("$directory/$file")) AND ($file!=".") AND ($file!="..")){
			tree("$directory/$file");
		}else{
			if($file != "." and $file != ".."){
				$dir_arr[] =  "$directory/$file";
			}
		}
	}
	$mydir->close();
	return $dir_arr;
}


/**
 * 获取客户端的ip地址
 */
function getRealIpAddr(){
	if(!empty($_SERVER['HTTP_X_REAL_IP'])){
		$ip = $_SERVER['HTTP_X_REAL_IP'];
	}elseif(!empty($_SERVER['HTTP_CLIENT_IP'])){
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	}elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	}else{
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return $ip;
}
/**
 * 根据ip地址获取所属地区
 * @param string $ip
 */
function getAreaByIP($ip=''){
	if($ip==''){
		$ip = getRealIpAddr();
	}
	require_once  (ORG."geoip/geoip.php");
	$ip_area = getIP_byGeo($ip);
	return $ip_area;
}

/**
 * 连接redis
 */
function redis($is_read = '') {
	if($is_read == 'read'){
		global $reids_read_config;
		$redis_config = $reids_read_config;
	}else{
		global $reids_write_config;
		$redis_config = $reids_write_config;
	}
	$redis = new Redis();
	$redis->connect($redis_config['host'],$redis_config['port']);
	if(!empty($redis_config['pass'])){
		$redis->auth($redis_config['pass']);
	}
	return $redis;
}


/**
 * 获取和设置配置参数 支持批量定义
 * @param string|array $name 配置变量
 * @param mixed $value 配置值
 * @return mixed
 */
function C($name=null, $value=null) {
	static $_config = array();
	// 无参数时获取所有
	if (empty($name)) {
		return $_config;
	}
	// 优先执行设置获取或赋值
	if (is_string($name)) {
		if (!strpos($name, '.')) {
			$name = strtolower($name);
			if (is_null($value))
			return isset($_config[$name]) ? $_config[$name] : null;
			$_config[$name] = $value;
			return;
		}
		// 二维数组设置和获取支持
		$name = explode('.', $name);
		$name[0]   =  strtolower($name[0]);
		if (is_null($value))
		return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null;
		$_config[$name[0]][$name[1]] = $value;
		return;
	}
	// 批量设置
	if (is_array($name)){
		$_config = array_merge($_config, array_change_key_case($name));
		return;
	}
	return null; // 避免非法参数
}

/**
 * A函数用于实例化Action 格式：[项目.]模块
 * @param string $name Action资源地址
 * @param string $layer 控制层名称
 * @param boolean $common 是否公共目录
 * @return Action|false
 */
function A($name,$layer='',$ext='.class.php'){
	static $_action = array();
	$name = ucfirst(strtolower($name));
	$layer = $layer?$layer:'control';
	if(strpos($name,'.')) {// 指定项目
		list($app) = explode('.',$name);
		$name = str_replace('.','/'.$layer.'/',$name);
	}else{
		$app = '@';
		$name = '@/'.$layer.'/'.$name;
	}

	if(isset($_action[$name]))  return $_action[$name];

	$class = basename($name.ucfirst($layer));

	if('@' == $app){
		$file_path = APP_ROOT.'/'.$layer.'/'.$class.$ext;
	}else{
		$file_path = MYMVC_ROOT.'/../'.$app.'/'.$layer.'/'.$class.$ext;
	}

	if(file_exists($file_path)){
		require_once($file_path);
	}else{
		return false;
	}

	if(class_exists($class,false)) {
		$action = new $class();
		$_action[$name] = $action;
		return $action;
	}else {
		return false;
	}
}

/**
 * M函数用于实例化一个没有模型文件的Model
 * @param string $name Model名称 支持指定基础模型 例如 MongoModel:User
 * @param string $tablePrefix 表前缀
 * @param mixed $connection 数据库连接信息
 * @return Model
 */
function M($name='', $tablePrefix='',$connection='') {
	static $_model  = array();
	if(strpos($name,':')) {
		list($class,$name)    =  explode(':',$name);
	}else{
		$class = 'Model';
	}
	$guid = $tablePrefix.$name . '_' . $class;
	if (!isset($_model[$guid]))
	$_model[$guid] = new $class($name,$tablePrefix,$connection);
	return $_model[$guid];
}

/**
 * D函数用于实例化Model 格式 [项目.]模块
 * @param string $name Model资源地址
 * @param string $layer 业务层名称
 * @return Model
 */
function D($name='',$layer='',$ext='.class.php') {
	if(empty($name)) return new Model;
	static $_model = array();
	$name = ucfirst(strtolower($name));
	$layer = $layer?$layer:'model';

	if(strpos($name,'.')) {// 指定项目
		list($app) = explode('.',$name);
		$name = str_replace('.','/'.$layer.'/',$name);
	}else{
		$app = '@';
		$name = '@/'.$layer.'/'.$name;
	}

	if(isset($_model[$name]))  return $_model[$name];

	$class = basename($name.ucfirst($layer));

	if('@' == $app){
		$file_path = APP_ROOT.'/'.$layer.'/'.$class.$ext;
	}else{
		$file_path = MYMVC_ROOT.'/../'.$app.'/'.$layer.'/'.$class.$ext;
	}

	if(file_exists($file_path)){
		require_once($file_path);
	}else{
		return false;
	}
	
	if(class_exists($class)) {
		$model = new $class(basename($name));
	}else {
		$model = new Model(basename($name));
	}
	$_model[$name]  =  $model;
	return $model;
}

/**  
 * 产生一个指定长度的随机字符串
 * @access public
 * @param int $len 产生字符串的位数  
 * @return string
 */
function randStr($len = 6){
	$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	mt_srand((double) microtime()*1000000*getmypid()); // seed the random number generater (must be done)
	$password = '';
	while(strlen($password)<$len)
		$password .= substr($chars,(mt_rand()%strlen($chars)),1);
	return $password;
}
/**
 * 生成文章url地址
 * 英文字符串
 */
function createurl($str_en){
	if(empty($str_en)){
		return $str_en;
	}
	$str_en = strtolower(trim($str_en));
	$str_url = preg_replace('/[^a-z0-9]+/i','-',$str_en);
	return $str_url;
}



//抓取https的url
function curl_get($url, $proxy = false){
	$ch = curl_init();
	$useragent = "Mozilla/5.0 (Windows NT 5.1; rv:11.0) Gecko/20100101 Firefox/11.0";
	$header = array('Accept-Language: en,zh;q=0.5','Connection: Keep-Alive','Cache-Control: no-cache','Host:fanyi.youdao.com');
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

	if ($proxy){
		$ip = "172.16.0.26";
		curl_setopt($ch, CURLOPT_PROXY, $ip);
	}
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 这两项设置是抓取https
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 是否抓取跳转后的页面

	$data = curl_exec($ch);
	curl_close($ch);
	if ($data)
		return $data;
	else
		return false;
}